package com.csust.travel.service;

import com.csust.travel.entity.NewUsers;
import com.csust.travel.exception.ServiceException;
import com.csust.travel.mapper.NewUsersMapper;
import com.csust.travel.util.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.rmi.server.ServerCloneException;

@Service
public class UserService {
    @Autowired
    NewUsersMapper newUsersMapper;


    public NewUsers login(NewUsers newUsers){
        NewUsers dbUser = newUsersMapper.findUserByUsername(newUsers.getUsername());
        if (dbUser ==null){
            throw new ServiceException("该用户未注册");
        }
        if (!newUsers.getPassword().equals(dbUser.getPassword())){
            throw new ServiceException("用户名或密码错误");
        }

        //生成 Token

        newUsersMapper.updateTime(dbUser.getId());
        String token = TokenUtils.createToken(dbUser.getId().toString(), dbUser.getPassword());
        dbUser.setToken(token);
        return dbUser;
    }

    public NewUsers register(NewUsers newUsers){
        NewUsers dbUser = newUsersMapper.findUserByUsername(newUsers.getUsername());
        if (dbUser !=null){
            throw new ServiceException("用户名已存在");
        }
        newUsers.setRole("用户");
        newUsersMapper.addUser(newUsers);

        return newUsers;
    }

}

